package com.hansen.library.ui.widget.image;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatImageView;
import android.util.AttributeSet;

import com.hansen.library.R;

/**
 * 宽高相等ImageView
 * Created by han on 2017/11/28 0028.
 */

public class SquareImageView extends AppCompatImageView {

    private boolean hasBorder;
    private int borderColor;
    private int borderWidth;

    private Paint paint;
    private Path path;

    public SquareImageView(Context context) {
        this(context,null);
    }

    public SquareImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public SquareImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.BorderStyleable, defStyleAttr, 0);

        hasBorder = a.getBoolean(R.styleable.BorderStyleable_xm_has_border, false);
        borderColor = a.getColor(R.styleable.BorderStyleable_xm_border_color, Color.parseColor("#CAC8C8"));
        borderWidth = a.getDimensionPixelSize(R.styleable.BorderStyleable_xm_border_width, 1);

        a.recycle();

        paint = new Paint();

        path = new Path();

        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(borderColor);
        paint.setStrokeWidth(borderWidth);
        paint.setAntiAlias(true);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        this.setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
        // Children are just made to fill our space.
        int childWidthSize = getMeasuredWidth();
        //设置高度与宽度一样
        heightMeasureSpec = widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (hasBorder) {
            path.moveTo(0, 0);
            path.lineTo(0, this.getWidth());
            canvas.drawPath(path, paint);

            path.moveTo(0, 0);
            path.lineTo(this.getHeight(), 0);
            canvas.drawPath(path, paint);

            path.moveTo(this.getWidth(), 0);
            path.lineTo(this.getWidth(), this.getHeight());
            canvas.drawPath(path, paint);

            path.moveTo(0 ,this.getHeight());
            path.lineTo(this.getWidth(), this.getHeight());

            canvas.drawPath(path, paint);
        }
    }
}
